//
//  EnterMessageController.m
//  Runone
//
//  Created by runone01 on 16/10/26.
//  Copyright © 2016年 runone. All rights reserved.
//

#import "EnterMessageController.h"
#import "UITextField+ToolBar.h"
#import "UITextView+ToolBar.h"
#import "ParModel.h"
#import "MJExtension.h"
#import "RequestHelper.h"
#import "IntVclDrivedRecordInfoModel.h"
#import "IntVclUserInfo.h"
#import "GeoViewController.h"
#import "PromptUtil.h"
#import "DateViewController.h"
#import "CommonUtility.h"
#import "VehiclePlanDetailViewController.h"
#import "CommonUtilityjudge.h"
#import "CarIdViewController.h"
#import "EKDateTimePickerView.h"
#import "NSDate+Extension.h"
#import "UIColor+Addition.h"
#import "RODateHelper.h"
#import "SVProgressHUD.h"

@interface EnterMessageController ()<UITextFieldDelegate,UIPopoverPresentationControllerDelegate,UITextViewDelegate>
@property (weak, nonatomic) IBOutlet UITextField *CarID;
@property (weak, nonatomic) IBOutlet UITextField *BeginTime;
@property (weak, nonatomic) IBOutlet UITextField *planEndTime;
@property (weak, nonatomic) IBOutlet UITextField *returnTime;
@property (weak, nonatomic) IBOutlet UITextView *startTo;
@property (weak, nonatomic) IBOutlet UITextView *ToEnd;
@property (weak, nonatomic) IBOutlet UITextField *Person;
@property (weak, nonatomic) IBOutlet UITextField *PersonNumber;
@property (weak, nonatomic) IBOutlet UITextField *Persons;
@property (weak, nonatomic) IBOutlet UITextView *UseCarDescription;
@property(nonatomic,strong)PromptUtil *pro;
@property(nonatomic,strong)DateViewController *dateVC;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *TVHight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *EndLocationHeight;
@property (weak, nonatomic) IBOutlet UIButton *startClearBtn;
@property (weak, nonatomic) IBOutlet UIButton *endClearBtn;
@property (weak, nonatomic) IBOutlet UITextView *descriptionTV;

@property(nonatomic)CGFloat startHeight;
@property(nonatomic)CGFloat endHeight;
@property(nonatomic,strong)GeoViewController *geo;
@property(nonatomic,copy)NSString *Htitle;
@property(nonatomic,copy)NSString *Hsubtitle;
@property(nonatomic,strong)CarIdViewController *carIdC;
@property (nonatomic, strong) NSDate *lastScrollDate;// 上一次滚动的时间
@end

@implementation EnterMessageController

#pragma   - - - --车辆录入界面



- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"%@",_CarIdArray);
    [self setInputOK];
    
    _startHeight=30;
    _endHeight=30;
//    self.title=@"车辆录入";
    UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 150, 30)];
    label.text=@"车辆录入";
    label.textAlignment=NSTextAlignmentCenter;
    label.textColor=[UIColor whiteColor];
    self.navigationItem.titleView=label;
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc] initWithTitle:@"提 交" style:UIBarButtonItemStylePlain target:self action:@selector(request)];
    _CarID.tag=0;
    _CarID.delegate=self;
    _BeginTime.delegate=self;
    _BeginTime.tag=1;
    _planEndTime.delegate=self;
    _planEndTime.tag=2;
    _returnTime.delegate=self;
    _returnTime.tag=3;
    _startTo.delegate=self;
    _ToEnd.delegate=self;
    _pro=[[PromptUtil alloc] init];
    
    _geo=[[GeoViewController alloc] init];
    _startTo.tag=1;
    _ToEnd.tag=2;
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
}
-(void)height:(NSString *)str Height:(NSLayoutConstraint *)height {

    CGFloat statrLocalHeight = [str boundingRectWithSize:CGSizeMake(_startTo.frame.size.width-40, MAXFLOAT)
                                                 options:NSStringDrawingUsesLineFragmentOrigin
                                              attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:13.f]}
                                                 context:nil].size.height;
    CGFloat returnHeight=statrLocalHeight+20;
    if (returnHeight==0) {
        height.constant=30.0f;
    }
    else{
    height.constant=returnHeight;
    }
}

//关闭键盘
-(void)returnKeyboard
{
    [_CarID resignFirstResponder];
    [_startTo resignFirstResponder];
    [_ToEnd  resignFirstResponder];
    [_Person resignFirstResponder];
    [_Persons resignFirstResponder];
    [_PersonNumber resignFirstResponder];
    [_descriptionTV resignFirstResponder];
    [_BeginTime resignFirstResponder];
    [_planEndTime resignFirstResponder];
    [_returnTime resignFirstResponder];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self returnKeyboard];
}
//出发地
- (IBAction)clearStartTV:(UIButton *)sender {
    _startTo.text=@"";
    _startClearBtn.hidden=YES;
    _TVHight.constant=30.f;
    [_startTo resignFirstResponder];
}
//目的地
- (IBAction)ClearEndTV:(UIButton *)sender {
    _ToEnd.text=@"";
    _EndLocationHeight.constant=30.f;
    _endClearBtn.hidden=YES;
    [_ToEnd resignFirstResponder];
}

-(void)textViewDidEndEditing:(UITextView *)textView
{
    if (_startTo.text.length==0) {
        [_startTo resignFirstResponder];
    }
    if (_ToEnd.text.length==0) {
        [_ToEnd resignFirstResponder];
    }
    
}

-(void)textViewDidBeginEditing:(UITextView *)textView
{
    if (textView.tag==1)
    {
    __weak typeof(self) weakself=self;
    _geo.TitleBlock=^(NSString *title){
            weakself.startTo.text=title;
        [weakself height:weakself.startTo.text Height:weakself.TVHight];
 
    };
        if (textView.text.length>0) {
            _startClearBtn.hidden=NO;
        }
        else
        {
            _startClearBtn.hidden=YES;
            [self.navigationController pushViewController:_geo animated:YES];
        }
    }
    
    if (textView.tag==2)
    {
        __weak typeof(self) weakself=self;
        _geo.TitleBlock=^(NSString *title){
            weakself.ToEnd.text=title;
             [weakself height:weakself.startTo.text Height:weakself.EndLocationHeight];
        };
        if (textView.text.length>0) {
            _endClearBtn.hidden=NO;
        }
        else
        {
            _endClearBtn.hidden=YES;
            [self.navigationController pushViewController:_geo animated:YES];
        }
    }
    
}


-(NSString *)dataValue
{
    IntVclDrivedRecordInfoModel *model=[[IntVclDrivedRecordInfoModel alloc] init];
    model.VehicleNo=_CarID.text;
    model.PlanDepartureTime=_BeginTime.text;
    model.PlanArrivalTime=_planEndTime.text;
    model.PlanReturnTime=_returnTime.text;
    model.Origin=_startTo.text;
    model.Destination=_ToEnd.text;
    model.Driver=_Person.text;
    model.DriverTel=_PersonNumber.text;
    
    NSMutableArray *mytable=[[NSMutableArray alloc] init];
    
    NSArray *personArray=[_Persons.text componentsSeparatedByString:@"，"];
    for (int i=0; i<personArray.count; i++)
    {
        IntVclUserInfo *yongcheren=[[IntVclUserInfo alloc] init];
        yongcheren.VclUserName=personArray[i];
        [mytable addObject:yongcheren];
    }
//    NSLog(@"%lu",mytable.count);
    model.IntVclUserInfoList=mytable;
    NSMutableDictionary *muDic=model.mj_keyValues;
    NSString *str = [muDic mj_JSONString];
    
    ParModel *parmodel=[[ParModel alloc] init];
    parmodel.key=@"IntVclDrivedRecordInfo";
    parmodel.value=str;
    
    NSMutableDictionary *jsdic=parmodel.mj_keyValues;
    NSString *model1 = jsdic.mj_JSONString;
    
    NSString *strl=@"[";
    NSString *temp=[strl stringByAppendingString:model1];
    NSString *str1r=@"]";
    NSString *JsonString=[temp stringByAppendingString:str1r];

    return JsonString;
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField.tag==1) {
        [_BeginTime resignFirstResponder];
    }
    if (textField ==_planEndTime) {
        [_planEndTime resignFirstResponder];
    }
    return YES;
}
//时间选择器
- (void) setUpDatePicker:(UITextField *)tf {
    
    EKDateTimePickerView *datepicker = [[EKDateTimePickerView alloc]initWithDatePosition:EKDatePositionMiddel CompleteBlock:^(NSDate *startDate) {
        _lastScrollDate = startDate;
        NSString *dateStr = [startDate stringWithOutTimeWithFormat:@"yyyy-MM-dd HH:mm:ss"];

        tf.text = dateStr;
        //        [sender setTitle:dateStr forState:UIControlStateNormal];
    }];
    datepicker.datePickerStyle = EKDateStyleShowYearMonthDayHourMinute;
    datepicker.themeColor      = [UIColor colorWithHexString:@"38b1dc"];
    if (tf.text != nil) {
        _lastScrollDate = nil;
        [datepicker scrollToSepicefyDate:[RODateHelper dateWithOutTimeZoneFromString:tf.text withFormat:nil] animated:NO];
    }
    
    if (_lastScrollDate != nil) {
        [datepicker scrollToSepicefyDate:_lastScrollDate animated:NO];
    }

    [datepicker show];
}
//出发时间
- (IBAction)BeginTimeBtn:(UIButton *)sender {
    [self returnKeyboard];
    [self setUpDatePicker:self.BeginTime];
}
//到达时间
- (IBAction)EndTimeBtn:(UIButton *)sender {
    [self returnKeyboard];
    [self setUpDatePicker:self.planEndTime];
}

//返程时间
- (IBAction)PlanTimeBtn:(UIButton *)sender { //returnTime
    [self returnKeyboard];
    [self setUpDatePicker:self.returnTime];
}

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    
    if (textField.tag==0) {
        __weak typeof(self) weakSelf=self;
        [self carList];
        [self presentViewController:_carIdC animated:YES completion:nil];
        _carIdC.CarIdBlock=^(NSString *str){
            weakSelf.CarID.text=str;
        };
       // [_CarID resignFirstResponder];
        return;
    }

    
}

-(void)datePick {
    _dateVC=[[DateViewController alloc] init];
    _dateVC.modalPresentationStyle=UIModalPresentationPopover;
    _dateVC.popoverPresentationController.sourceView=self.view;
    _dateVC.popoverPresentationController.sourceRect=DateFrame;
    _dateVC.popoverPresentationController.permittedArrowDirections=NO;
    _dateVC.popoverPresentationController.delegate=self;
    
}
//车牌号
-(void)carList
{
    _carIdC=[[CarIdViewController alloc] init];
    _carIdC.dataSource=_CarIdArray;
    _carIdC.modalPresentationStyle=UIModalPresentationPopover;
    _carIdC.popoverPresentationController.sourceView=self.CarID;
    _carIdC.popoverPresentationController.sourceRect=CGRectMake(80, 190, 0, 0);
    _carIdC.popoverPresentationController.permittedArrowDirections=NO;
    _carIdC.popoverPresentationController.delegate=self;
}

//提交判断是否有效
-(void)request
{
    if (_CarID.text.length==0) {
        [_pro alert:@"请输入车牌号"];
        return;
    }
    if (_CarID.text.length>70) {
        [_pro alert:@"请输入有效车牌号"];
        return;
    }
    if (![self validateCarNo:_CarID.text]) {
        [_pro alert:@"请输入有效的车牌号码"];
        return;
    }
    
    if(!stringIsEmpty(_PersonNumber.text)&&!validatePhone(_PersonNumber.text))
    {
        [_pro alert:@"请输入有效的电话号码"];
        return;
    }
   
    int timeCompare=[_BeginTime.text compare:_planEndTime.text];
    if (timeCompare==0) {
        [_pro alert:@"开始时间不能等于结束时间！~"];
        return ;
    }
    if (timeCompare>0) {
        [_pro alert:@"出发时间不能大于计划到达时间！~"];
        return;
    }
   int returnTime=[_planEndTime.text compare:_returnTime.text]; 
    if (returnTime>0) {
        [_pro alert:@"返程时间不能小于计划到达时间！~"];
        return;
    }
    
    if (_startTo.text.length == 0) {
     [_pro alert:@"出发地不能为空"];
        return;
    }
    
    if (_ToEnd.text.length == 0) {
        [_pro alert:@"目的地不能为空"];
    }
    
    if(_Person.text.length == 0) {
        [_pro alert:@"司机不能为空"];
        return;
    }
    
    if (_PersonNumber.text.length == 0) {
        [_pro alert:@"司机电话不能为空"];
        return;
    }
    
    if (_Persons.text.length ==0 ) {
        [_pro alert:@"用车人不能为空"];
        return;
    }
    if (_Person.text.length > 100) {
        [_pro alert:@"用车人长度不能超过100"];
        return;
    }
    
    RequestHelper *requestHelper=[[RequestHelper alloc] init];
    RequestGinsengModel *getCurrentEventModel=[[RequestGinsengModel alloc] init];
    getCurrentEventModel.URL=GetCarManagerEnterMessageURL;
    getCurrentEventModel.DataValue= [self dataValue];
    getCurrentEventModel.UpdatedTime=[requestHelper getCurrentTime];
    getCurrentEventModel.SystemCode=@"GuangleHighway";
    getCurrentEventModel.MethodName=@"InputIntVclDrivedRecordInfo";
    requestHelper.block=^(RequestOutginseng *requestOutginseng,id dataValueModel){
        
        if ([requestOutginseng.Code isEqualToString:@"001"]) {
            _CarID.text=@"";
            _BeginTime.text=@"";
            _planEndTime.text=@"";
            _returnTime.text=@"";
            _ToEnd.text=@"";
            _startTo.text=@"";
            _Person.text=@"";
            _Persons.text=@"";
            _PersonNumber.text=@"";
            _descriptionTV.text=@"";
            _startClearBtn.hidden=YES;
            _endClearBtn.hidden=YES;
            VehiclePlanDetailViewController *detail=[[VehiclePlanDetailViewController alloc] init];
            [self.navigationController pushViewController:detail animated:YES];
//            NSLog(@"w");
        }
        else {
            [SVProgressHUD showErrorWithStatus:@"录入失败"];
            return ;
        }
    };
    [requestHelper RequestGinsengModel:getCurrentEventModel andPushController:self];
}

- (BOOL)validateCarNo:(NSString*)carNo
{
    
    NSString *carRegex =@"^[\u4e00-\u9fa5]{1}[a-zA-Z]{1}[a-zA-Z_0-9]{4}[a-zA-Z_0-9_\u4e00-\u9fa5]$";
    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",carRegex];
    //    NSLog(@"carTest is %@",carTest);
    if ([carTest evaluateWithObject:carNo]) {
        return YES;
    }else{
        return NO;
    }
}

-(void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden=NO;
    self.tabBarController.tabBar.hidden=YES;
}

-(void)setInputOK {
    [_CarID setTextFieldInputAccessoryView:_CarID frame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    [_BeginTime setTextFieldInputAccessoryView:_BeginTime frame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    [_planEndTime setTextFieldInputAccessoryView:_planEndTime frame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    [_returnTime setTextFieldInputAccessoryView:_returnTime frame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    [_startTo setTextFieldInputAccessoryView:_startTo frame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    [_ToEnd setTextFieldInputAccessoryView:_ToEnd frame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    [_Person setTextFieldInputAccessoryView:_Person frame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    [_PersonNumber setTextFieldInputAccessoryView:_PersonNumber frame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    [_Persons setTextFieldInputAccessoryView:_Persons frame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    [_UseCarDescription setTextFieldInputAccessoryView:_UseCarDescription frame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
}

-(UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller
{
    return UIModalPresentationNone;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
